package com.bdqn.t330.ch04.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//过滤器 S2 JSP 学过
//    过滤器只能拦截url级别的网络请求
//      例如：www.baidu.com/login.jsp
//           www.baidu.com/login   (servlet)
//           www.baidu.com/login.jpg  www.baidu.com/login.js
//        1、统一设置post字符集编码
//        2、判断用户是否登录，session是否存在
//        过滤器是依赖Servlet
//实现方式 1、启动类@ServletComponentScan  @Slf4j @WebFilter(urlPatterns = "*.jsp")
//       2、直接利用springboot去实现filter

//@Slf4j
//@WebFilter(urlPatterns = "*.jsp")
public class SessionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("filter执行方法");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (httpServletRequest.getSession().getAttribute("user") == null) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.sendRedirect("/t330/login.jsp");
        } else {
            chain.doFilter(request, response);
        }

    }
}
